package com.edu.service.impl;

import com.edu.dao.BookDao;
import com.edu.dao.CartsDao;
import com.edu.dao.OrdersDao;
import com.edu.dao.impl.BookDaoImpl;
import com.edu.dao.impl.CartsDaoImpl;
import com.edu.dao.impl.OrdersDaoImpl;
import com.edu.entity.OrderDetailEntity;
import com.edu.service.CartsService;

import java.util.LinkedList;

/**
 * com.edu.service.impl
 * 2024/7/11 9:43
 *
 * @author Fancy
 * @version 1.0
 */
public class CartsServiceImpl implements CartsService {
    private final CartsDao cartsDao;
    private final OrdersDao ordersDao;

    private final BookDao bookDao;

    public CartsServiceImpl(){
        this.cartsDao = new CartsDaoImpl();
        this.ordersDao = new OrdersDaoImpl();
        this.bookDao = new BookDaoImpl();
    }

    public LinkedList<OrderDetailEntity> getCartItemByUserId(int userId) {
        int orderId = ordersDao.getOrderIdNoSettled(userId);
        if(orderId == -1){
            //没有未完成的订单则新建一个购物车
            ordersDao.createOrder(userId);
            orderId = ordersDao.getOrderIdNoSettled(userId);
        }
        LinkedList<OrderDetailEntity> carts = cartsDao.getCartItemByOrderId(orderId);
        for (OrderDetailEntity cart :
                carts) {
            cart.setBook(bookDao.getBookInfoById(cart.getBookId()));
        }
        return carts;
    }

    @Override
    public int addToCart(OrderDetailEntity cart, int userId) {
        int orderId = ordersDao.getOrderIdNoSettled(userId);
        if(orderId == -1){
            ordersDao.createOrder(userId);
            orderId = ordersDao.getOrderIdNoSettled(userId);
        }
        cart.setOrderId(orderId);
        cart.setUnitPrice(bookDao.getPriceByBookId(cart.getBookId()));
        return cartsDao.addToCart(cart);
    }

    @Override
    public int updateCartItemQuantity(int userId, int cartItemId, int quantity) {
        int orderId = ordersDao.getOrderIdNoSettled(userId);
        if(orderId == -1){
            return 0;
        }
        return cartsDao.updateCartItemQuantity(orderId, cartItemId, quantity);
    }

    @Override
    public int deleteCartItem(int userId, int cartItemId) {
        int orderId = ordersDao.getOrderIdNoSettled(userId);
        if(orderId == -1){
            return 0;
        }
        return cartsDao.deleteCartItem(orderId, cartItemId);
    }
}
